<?php
/**
 * mysql类
 */
if (!defined('ROOT_DIR')) exit('Access Denied!');

class mysql
{
	private $currentTable = null; //当前操作的表
	private $link = false; //连接数据库标识
	private $re = false;  //当前查询结果集
        private static $instance = null;
 
	public function __construct()
	{
            $this->connect();
	}

	/**
	 * 获取单例
	 *
	 * @return resource
	 */
        public static function getInstance(){
		if(!self::$instance){
			self::$instance = new self();
		}
		return self::$instance;
	}
        /**
	 * 连接数据库
	 *
	 * @return resource
	 */
         private function connect()
         {
              $config = Core::getConfig('db');
              if(empty($config['host'])){
                  exception_handler('数据库没有配置');
              }
              if( $config['pconnect']){
                     $this->link = @mysql_pconnect( $config['host'], $config['user'], $config['password'] );
              }else{
                     $this->link = @mysql_connect( $config['host'], $config['user'], $config['password'] );
              }
              if(!$this->link){
                    exception_handler('Can not connect to MySQL server');
              }
              $this->query("SET NAMES '".$config['charset']."'");
              $this->select_db( $config['name'] );
         }
	/**
	 * 注册表
	 * @param $table 表全名，作为当前数据操作的对象
	 */
	public function from( $table=NULL )
	{
		if (empty($table)){
			return false;
		}
		$this->currentTable = $table;
                return $this;
	}

	/**
	 * 检查表是否已经注册
	 */
	public function is_set()
	{
		return isset($this->currentTable);
	}

	/**
	 * 查询
	 * @param $filed字段，$where条件, $order排序, $group分组, $offset提取记录位置, $limit提取条数
	 * @return result
	 */
	public function select( $where=null, $filed=null, $order=null, $group=null, $offset=null, $limit=null )
	{
		if ( !$this->is_set() ){
			exception_handler('未注册要操作的表');
		}
		$sql = "";
		#条件
		$sql .= $where==null ? '' : ' WHERE ' . $where;
		#字段
		$filed = $filed==null ? '*' : $filed;
		#排序
		$sql .= $order==null ? '' : ' ORDER BY ' . $order;
		#分组
		$sql .= $group==null ? '' : ' GROUP BY ' . $group;
		#LIMIT
		if(is_numeric($offset)){
			$sql .= (is_numeric($limit) && $offset >= 0 && $limit > 0) ? " LIMIT " . $offset . ", " . $limit : "";
		}else{
			$sql .= (is_numeric($limit) && $limit > 0) ? " LIMIT  " . $limit : "";
		}
		$sql = "SELECT $filed FROM " . $this->currentTable . $sql;
		$re = $this->query( $sql );
		$this->re=$re;
		return $this;
	}
  
  /**
	 * 无须返回结果，只要判断真假
	 * @return bool
	 */
	public function is()
	{
		if(mysql_num_rows($this->re)>0){
			return true;
		}else{
			return false;
		}
	}
	 
  /**
	 * 取单条记录
	 * @return array
	 */
	public function fetch()
	{
		if($this->re){
			$data=$this->fetch_array($this->re);
			return $data;
		}else{
			return false;
		}
	}
	
	/**
	 * 取多条记录
	 * @return array
	 */
	 
	public function fetchAll()
	{
		if($this->re){
			$data=array();
			while($row=$this->fetch_array($this->re)){
				array_push($data,$row);
			}
			return $data;
		}else{
			return false;
		}
	}
	
	/**
	 * 插入单条、多条记录
	 * @param $array 字段跟值对应的一维或者两维数组
	 * @return integer 最后插入记录的id
	 */
	public function insert($array)
	{
		if (!$this->is_set()){
			exception_handler('未注册要操作的表');
		}
		if (!is_array($array) || count($array)<=0) {
			return false;
		}
		if(!is_array($array[0])){
			//如果为一维数组 加多一维统一为二维处理
			$array=array($array);
		}
		$keys = array_keys($array[0]);
		$field = implode(",", $keys);

		$d = array();
		foreach($array as $key => $val)
		{
			$d[] = "('".implode("','", $val)."')";
		}
		$sql = "INSERT INTO " . $this->currentTable . "($field) VALUES ".implode(",", $d);
		$this->query( $sql );
		$id = $this->insert_id();
		return $id;
	}

	/**
	 * 更新
	 * @param $array 字段跟值对应的数组, $where更新条件
	 * @return bool
	 */
	public function update( $array, $where=null )
	{
		if ( !$this->is_set() ){
			exception_handler('未注册要操作的表');
		}
		if ( !is_array( $array ) ) {
			return false;
		}
		$param = array();
		foreach( $array as $key => $val )
		{
			$param[] = $key . "='" . $val . "'";
		}
		$string = implode( ",", $param );
		$where = ($where==null)? "" : " WHERE " . $where;
		$sql .= "UPDATE " . $this->currentTable . " SET " . $string . $where;
		$this->query( $sql );
		if ( $this->affected_rows() >= 0 ){
			return true;
		}else{
			return false;
		}
	}
  

	/**
	 * 删除
	 * @param $where更新条件
	 * @return bool
	 */
	public function delete( $where=null )
	{
		if ( !$this->is_set() )
			exception_handler( '未注册要操作的表');
		$sWhere = $where==null ? "" : " WHERE " . $where;
		$sql .= "DELETE FROM " . $this->currentTable . $sWhere;
		$this->query( $sql );
		if ( $this->affected_rows() > 0 ){
			return true;
		}else{
			return false;
		}
	}

	//取出数据库里面的表
	private function showTables()
	{
		$r = $this->query('SHOW TABLES');
		$d = array();
		while( $row = $this->fetch_row($r) ){
			$d[$row[0]] = strtolower($row[0]);
		}
		return $d;
	}

	//取出表里面的字段信息
	public function showFields($table)
	{
		$r = $this->query('DESC ' . $table);
		$d = array();
		while( $row = $this->fetch_array($r) ){
			$d[$row['Field']] = $row;
		}
		return $d;
	}

	private function select_db($dbname)
	{
		return mysql_select_db($dbname);
	}

	public function query($sql)
	{
		$query = @mysql_query($sql);
		if(!$query)
		{
			exception_handler('MySQL Query Error', $sql);
		}
		return $query;
	}


	public function fetch_array($query, $result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array($query, $result_type);
	}


	public function affected_rows()
	{
		return mysql_affected_rows();
	}

	
	public function insert_id()
	{
		return mysql_insert_id();
	}
}

?>